// pages/index/avatar.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        checked: 0,
        itemId: 1,
        index: 0,
        canvas: {},
        range: {},
        graph1: {},
        graph2: {},
        itemList: [],
        tabs: [{
                key: 1,
                name: "国庆",
                templates: [{
                        id: 1001,
                        name: "",
                        src: "../../images/1/1.png",
                        type: "1"
                    },
                    {
                        id: 1002,
                        name: "",
                        src: "../../images/1/2.png",
                        type: "1"
                    },
                    {
                        id: 1003,
                        name: "",
                        src: "../../images/1/3.png",
                        type: "1"
                    },
                    {
                        id: 1004,
                        name: "",
                        src: "../../images/1/4.png",
                        type: "1"
                    },
                    {
                        id: 1005,
                        name: "",
                        src: "../../images/1/5.png",
                        type: "1"
                    },
                    {
                        id: 1006,
                        name: "",
                        src: "../../images/1/6.png",
                        type: "1"
                    },
                    {
                        id: 1007,
                        name: "",
                        src: "../../images/1/7.png",
                        type: "1"
                    },
                    {
                        id: 1008,
                        name: "",
                        src: "../../images/1/8.png",
                        type: "1"
                    },
                    {
                        id: 1009,
                        name: "",
                        src: "../../images/1/9.png",
                        type: "1"
                    },
                    {
                        id: 1010,
                        name: "",
                        src: "../../images/1/10.png",
                        type: "1"
                    },
                    {
                        id: 1011,
                        name: "",
                        src: "../../images/1/11.png",
                        type: "1"
                    },
                    {
                        id: 1012,
                        name: "",
                        src: "../../images/1/12.png",
                        type: "1"
                    },
                    {
                        id: 1013,
                        name: "",
                        src: "../../images/1/13.png",
                        type: "1"
                    },
                    {
                        id: 1014,
                        name: "",
                        src: "../../images/1/14.png",
                        type: "1"
                    },
                    {
                        id: 1015,
                        name: "",
                        src: "../../images/1/15.png",
                        type: "1"
                    },
                    {
                        id: 1016,
                        name: "",
                        src: "../../images/1/16.png",
                        type: "1"
                    },
                    {
                        id: 1017,
                        name: "",
                        src: "../../images/1/17.png",
                        type: "1"
                    },
                    {
                        id: 1018,
                        name: "",
                        src: "../../images/1/18.png",
                        type: "1"
                    },
                    {
                        id: 1019,
                        name: "",
                        src: "../../images/1/19.png",
                        type: "1"
                    },
                    {
                        id: 1020,
                        name: "",
                        src: "../../images/1/20.png",
                        type: "1"
                    },
                    {
                        id: 1021,
                        name: "",
                        src: "../../images/1/21.png",
                        type: "1"
                    }
                ]
            },
            {
                key: 2,
                name: "春节",
                templates: [{
                        id: 2001,
                        name: "",
                        src: "../../images/2/1.png",
                        type: "2"
                    },
                    {
                        id: 2002,
                        name: "",
                        src: "../../images/2/2.png",
                        type: "2"
                    },
                    {
                        id: 2003,
                        name: "",
                        src: "../../images/2/3.png",
                        type: "2"
                    },
                    {
                        id: 2004,
                        name: "",
                        src: "../../images/2/4.png",
                        type: "2"
                    },
                    {
                        id: 2005,
                        name: "",
                        src: "../../images/2/5.png",
                        type: "2"
                    },
                    {
                        id: 2006,
                        name: "",
                        src: "../../images/2/6.png",
                        type: "2"
                    },
                    {
                        id: 2007,
                        name: "",
                        src: "../../images/2/7.png",
                        type: "2"
                    },
                    {
                        id: 2008,
                        name: "",
                        src: "../../images/2/8.png",
                        type: "2"
                    },
                    {
                        id: 2009,
                        name: "",
                        src: "../../images/2/9.png",
                        type: "2"
                    },
                    {
                        id: 2010,
                        name: "",
                        src: "../../images/2/10.png",
                        type: "2"
                    },
                    {
                        id: 2011,
                        name: "",
                        src: "../../images/2/11.png",
                        type: "2"
                    },
                    {
                        id: 2012,
                        name: "",
                        src: "../../images/2/12.png",
                        type: "2"
                    },
                    {
                        id: 2013,
                        name: "",
                        src: "../../images/2/13.png",
                        type: "2"
                    },
                    {
                        id: 2014,
                        name: "",
                        src: "../../images/2/14.png",
                        type: "2"
                    },
                    {
                        id: 2015,
                        name: "",
                        src: "../../images/2/15.png",
                        type: "2"
                    },
                    {
                        id: 2016,
                        name: "",
                        src: "../../images/2/16.png",
                        type: "2"
                    },
                    {
                        id: 2017,
                        name: "",
                        src: "../../images/2/17.png",
                        type: "2"
                    },
                    {
                        id: 2018,
                        name: "",
                        src: "../../images/2/18.png",
                        type: "2"
                    },
                    {
                        id: 2019,
                        name: "",
                        src: "../../images/2/19.png",
                        type: "2"
                    },
                    {
                        id: 2020,
                        name: "",
                        src: "../../images/2/20.png",
                        type: "2"
                    }

                ]
            }, {
                key: 3,
                name: "圣诞节",
                templates: [{
                        id: 3001,
                        name: "",
                        src: "../../images/3/1.png",
                        type: "2"
                    },
                    {
                        id: 3002,
                        name: "",
                        src: "../../images/3/2.png",
                        type: "2"
                    },
                    {
                        id: 3003,
                        name: "",
                        src: "../../images/3/3.png",
                        type: "2"
                    },
                    {
                        id: 3004,
                        name: "",
                        src: "../../images/3/4.png",
                        type: "2"
                    },
                    {
                        id: 3005,
                        name: "",
                        src: "../../images/3/5.png",
                        type: "2"
                    },
                    {
                        id: 3006,
                        name: "",
                        src: "../../images/3/6.png",
                        type: "2"
                    },
                    {
                        id: 3007,
                        name: "",
                        src: "../../images/3/7.png",
                        type: "2"
                    },
                    {
                        id: 3008,
                        name: "",
                        src: "../../images/3/8.png",
                        type: "2"
                    },
                    {
                        id: 3009,
                        name: "",
                        src: "../../images/3/9.png",
                        type: "2"
                    },
                    {
                        id: 3010,
                        name: "",
                        src: "../../images/3/10.png",
                        type: "2"
                    },
                    {
                        id: 3011,
                        name: "",
                        src: "../../images/3/11.png",
                        type: "2"
                    },
                    {
                        id: 3012,
                        name: "",
                        src: "../../images/3/12.png",
                        type: "2"
                    },
                    {
                        id: 3013,
                        name: "",
                        src: "../../images/3/13.png",
                        type: "2"
                    },
                    {
                        id: 3014,
                        name: "",
                        src: "../../images/3/14.png",
                        type: "2"
                    },
                    {
                        id: 3015,
                        name: "",
                        src: "../../images/3/15.png",
                        type: "2"
                    },
                    {
                        id: 3016,
                        name: "",
                        src: "../../images/3/16.png",
                        type: "2"
                    },
                    {
                        id: 3017,
                        name: "",
                        src: "../../images/3/17.png",
                        type: "2"
                    },
                    {
                        id: 3018,
                        name: "",
                        src: "../../images/3/18.png",
                        type: "2"
                    },
                    {
                        id: 3019,
                        name: "",
                        src: "../../images/3/19.png",
                        type: "2"
                    },
                    {
                        id: 3020,
                        name: "",
                        src: "../../images/3/20.png",
                        type: "2"
                    },
                    {
                        id: 3021,
                        name: "",
                        src: "../../images/3/11.png",
                        type: "2"
                    },
                    {
                        id: 3022,
                        name: "",
                        src: "../../images/3/12.png",
                        type: "2"
                    },
                    {
                        id: 3023,
                        name: "",
                        src: "../../images/3/13.png",
                        type: "2"
                    },
                    {
                        id: 3024,
                        name: "",
                        src: "../../images/3/14.png",
                        type: "2"
                    },
                    {
                        id: 3025,
                        name: "",
                        src: "../../images/3/15.png",
                        type: "2"
                    },
                    {
                        id: 3026,
                        name: "",
                        src: "../../images/3/16.png",
                        type: "2"
                    },
                    // {
                    //     id: 3027,
                    //     name: "",
                    //     src: "../../images/3/17.png",
                    //     type: "2"
                    // },
                    // {
                    //     id: 3028,
                    //     name: "",
                    //     src: "../../images/3/18.png",
                    //     type: "2"
                    // },
                    {
                        id: 3029,
                        name: "",
                        src: "../../images/3/19.png",
                        type: "2"
                    },
                    {
                        id: 3030,
                        name: "",
                        src: "../../images/3/20.png",
                        type: "2"
                    }
                ]
            }
        ],
        templateSelect: undefined
    },
    bindChange: function (e) {
        this.setData({
            checked: e.detail.current
        });
    },
    navTip: function (e) {
        if (this.data.checked === e.target.dataset.idx) {
            return false;
        } else {
            this.setData({
                checked: e.target.dataset.idx
            })
        }
    },
    uploadImg() {
        let that = this;
        wx.chooseMedia({
            count: 1,
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
            success(res) {
                // console.log(res);
                // tempFilePath可以作为img标签的src属性显示图片
                // that.setDropItem({
                //     url: res.tempFiles[0]
                // });
                that.setData({
                    graph1: res.tempFiles[0]
                });
                // console.log(that.data.item);
                that.synthesis(); // 调用合成图方法
            }
        })
    },
    createImage() {
        this.clear();
        if (!this.data.graph1.tempFilePath) {
            // wx.showToast({
            //     icon: "error",
            //     title: '请上传头像'
            // })
            return false;
        }
        //this.drawImage("1", this.data.graph1.tempFilePath, 200, 200);
    },
    init(res) {
        const width = res[0].width
        const height = res[0].height
        const canvas = res[0].node
        const ctx = canvas.getContext('2d')
        const dpr = wx.getSystemInfoSync().pixelRatio
        canvas.width = width * dpr
        canvas.height = height * dpr
        ctx.scale(dpr, dpr)
        // console.log("width:" + canvas.width);
        // console.log("height:" + canvas.height);
        ctx.fillStyle = 'rgba(0, 0, 0, 0)';
        ctx.fillRect(0, 0, 200, 200);
        this.setData({
            canvas: canvas
        })
        // console.log(canvas);
        // console.log(ctx);
    },

    // 设置图片的信息
    setDropItem(imgPath) {
        let data = {}; // 存储图片信息
        let itemId = this.data.itemId;
        let canvas = this.data.canvas;
        let graph1 = this.data.graph1;
        let range = this.data.range;
        // console.log(graph1)
        // 获取图片信息，网络图片需先配置download域名才能生效
        // console.log(imgPath)
        wx.getImageInfo({
            src: imgPath,
            success: res => {
                // 初始化数据
                let maxWidth = 100,
                    maxHeight = 100; // 设置最大宽高
                if (res.width > maxWidth || res.height > maxHeight) { // 原图宽或高大于最大值就执行
                    if (res.width / res.height > maxWidth / maxHeight) { // 判断比例使用最大值的宽或高作为基数计算
                        data.width = maxWidth;
                        data.height = Math.round(maxWidth * (res.height / res.width));
                    } else {
                        data.height = maxHeight;
                        data.width = Math.round(maxHeight * (res.width / res.height));
                    }
                }
                data.image = imgPath; // 显示地址
                data.initImage = imgPath; // 原始地址
                data.id = ++itemId; // id
                // console.log(canvas._top)
                // console.log(canvas._left)
                data.top = 0 + range.top + data.width / 2; // top定位
                data.left = 0 + range.left + data.height / 2; // left定位
                // 圆心坐标
                data.x = data.left - (range.left) + data.width / 2;
                data.y = data.top - (range.top) + data.height / 2;
                data.scale = 1; // scale缩放
                data.rotate = 1; // 旋转角度
                data.active = false; // 选中状态
                // items[items.length] = data; // 每增加一张图片数据增加一条信息
                let items = this.data.itemList;
                items.push(data);
                this.setData({
                    itemList: items,
                    itemId: itemId
                })
                // console.log(this.data.itemList);
            }
        })
    },
    drawImage(id, imageUrl, x, y, width, heigth) {
        let canvas = this.data.canvas;
        const ctx = canvas.getContext('2d')

        let pic = canvas.createImage();
        pic.src = imageUrl; //可以是本地，也可以是网络图片
        pic.id = id;
        pic.onload = () => {
            ctx.drawImage(pic, x, y, width, heigth);
        }
    },
    handGraph2(e) {
        let that = this;
        if (e.target.dataset.type == 1) {
            that.setData({
                graph2: {
                    tempFilePath: e.target.dataset.path
                }
            });
        }
        if (e.target.dataset.type == 2) {
            that.setDropItem(e.target.dataset.path);
        }
        this.synthesis();
        // console.log(this.data.graph2);
    },
    saveImage() {
        let canvas = this.data.canvas;
        wx.showLoading({
            title: '保存中...',
        })
        wx.canvasToTempFilePath({
            canvas,
            success: res => {
                // 生成的图片临时文件路径
                const tempFilePath = res.tempFilePath
                wx.saveImageToPhotosAlbum({
                    filePath: tempFilePath, //res.tempFilePath
                    //保存成功失败之后，都要隐藏画板，否则影响界面显示。
                    success: (res) => {
                        wx.hideLoading();
                        wx.showToast({
                            title: '保存成功',
                            icon: 'none'
                        })
                    },
                    fail: (err) => {
                        wx.hideLoading();
                        wx.showModal({
                            title: '提示',
                            content: '保存图片需要允许访问相册权限！'
                        })
                        console.log(err)
                    }
                })
            },
        })
    },
    clear() {
        const canvas = this.data.canvas;
        const ctx = canvas.getContext('2d')
        ctx.clearRect(0, 0, 200, 200);
    },
    // 点击图片
    WraptouchStart: function (e) {
        let items = this.data.itemList;
        let index = this.data.index;
        // 循环图片数组获取点击的图片信息
        for (let i = 0; i < items.length; i++) {
            items[i].active = false;
            if (e.currentTarget.dataset.id == items[i].id) {
                index = i;
                items[index].active = true;
            }
        }
        // 获取点击的坐标值
        items[index].lx = e.touches[0].clientX;
        items[index].ly = e.touches[0].clientY;

        // console.log(items[index]);
        this.setData({
            itemList: items,
            index: index
        })
    },
    // 拖动图片
    WraptouchMove(e) {
        let items = this.data.itemList;
        let index = this.data.index;
        let graph1 = this.data.graph1;
        //  console.log(items[index]);
        items[index]._lx = e.touches[0].clientX;
        items[index]._ly = e.touches[0].clientY;
        // console.log(items[index].width + " " + items[index].height);
        // console.log(items[index].x + " " + items[index].y);
        items[index].left += items[index]._lx - items[index].lx;
        items[index].x += items[index]._lx - items[index].lx;

        items[index].top += items[index]._ly - items[index].ly;
        items[index].y += items[index]._ly - items[index].ly;

        items[index].lx = e.touches[0].clientX;
        items[index].ly = e.touches[0].clientY;

        this.setData({
            itemList: items,
            index: index
        })
    },
    // 放开图片
    WraptouchEnd() {
        this.synthesis(); // 调用合成图方法
    },
    // 点击伸缩图标
    oTouchStart(e) {
        let items = this.data.itemList;
        let index = this.data.index;
        let range = this.data.range;
        //找到点击的那个图片对象，并记录
        for (let i = 0; i < items.length; i++) {
            items[i].active = false;
            if (e.currentTarget.dataset.id == items[i].id) {
                index = i;
                items[index].active = true;
            }
        }
        //获取作为移动前角度的坐标
        items[index].tx = e.touches[0].clientX;
        items[index].ty = e.touches[0].clientY;
        //移动前的角度
        items[index].anglePre = this.countDeg(items[index].x, items[index].y, items[index].tx, items[index].ty);
        //获取图片半径
        items[index].r = this.getDistancs(items[index].x, items[index].y, items[index].left, items[index].top);
    },
    oTouchMove: function (e) {
        let items = this.data.itemList;
        let index = this.data.index;
        let range = this.data.range;
        //记录移动后的位置
        items[index]._tx = e.touches[0].clientX;
        items[index]._ty = e.touches[0].clientY;
        // console.log(items[index]._tx + "," + items[index]._ty);

        //移动的点到圆心的距离
        items[index].disPtoO = this.getDistancs(items[index].x, items[index].y, items[index]._tx - range.left, items[index]._ty - range.top)
        items[index].scale = items[index].disPtoO / items[index].r;

        //移动后位置的角度
        items[index].angleNext = this.countDeg(items[index].x, items[index].y, items[index]._tx, items[index]._ty)
        //角度差
        items[index].new_rotate = items[index].angleNext - items[index].anglePre;

        //叠加的角度差
        items[index].rotate += items[index].new_rotate;
        items[index].angle = items[index].rotate; //赋值

        //用过移动后的坐标赋值为移动前坐标
        items[index].tx = e.touches[0].clientX;
        items[index].ty = e.touches[0].clientY;
        items[index].anglePre = this.countDeg(items[index].x, items[index].y, items[index].tx, items[index].ty)

        //赋值setData渲染
        this.setData({
            itemList: items
        })
        this.synthesis();
    },
    // 计算坐标点到圆心的距离
    getDistancs(cx, cy, pointer_x, pointer_y) {
        var ox = pointer_x - cx;
        var oy = pointer_y - cy;
        return Math.sqrt(
            ox * ox + oy * oy
        );
    },
    /*
     *参数cx和cy为图片圆心坐标
     *参数pointer_x和pointer_y为手点击的坐标
     *返回值为手点击的坐标到圆心的角度
     */
    countDeg: function (cx, cy, pointer_x, pointer_y) {
        var ox = pointer_x - cx;
        var oy = pointer_y - cy;
        var to = Math.abs(ox / oy);
        var angle = Math.atan(to) / (2 * Math.PI) * 360;
        if (ox < 0 && oy < 0) //相对在左上角，第四象限，js中坐标系是从左上角开始的，这里的象限是正常坐标系  
        {
            angle = -angle;
        } else if (ox <= 0 && oy >= 0) //左下角,3象限  
        {
            angle = -(180 - angle)
        } else if (ox > 0 && oy < 0) //右上角，1象限  
        {
            angle = angle;
        } else if (ox > 0 && oy > 0) //右下角，2象限  
        {
            angle = 180 - angle;
        }
        return angle;
    },
    //删除图层
    deleteItem: function (e) {
        let items = this.data.itemList;
        let newList = [];
        for (let i = 0; i < items.length; i++) {
            if (e.currentTarget.dataset.id != items[i].id) {
                newList.push(items[i])
            }
        }
        if (newList.length > 0) {
            newList[newList.length - 1].active = true; // 剩下图片组最后一个选中
        }
        items = newList;
        this.setData({
            itemList: items
        })
    },
    synthesis(e) { // 合成图片
        this.clear();
        let items = this.data.itemList;
        let canvas = this.data.canvas;
        const ctx = canvas.getContext('2d')
        if (this.data.graph1.tempFilePath) {
            let pic = canvas.createImage();
            pic.src = this.data.graph1.tempFilePath; //可以是本地，也可以是网络图片
            pic.id = "graph1";
            pic.onload = () => {
                ctx.drawImage(pic, 0, 0, 200, 200);
            }
        }
        if (this.data.graph2.tempFilePath) {
            // this.drawImage("bk", this.data.graph2.tempFilePath, 0, 0, 200, 200);
            // console.log("graph2");
            let pic = canvas.createImage();
            pic.src = this.data.graph2.tempFilePath; //可以是本地，也可以是网络图片
            pic.id = "graph2";
            pic.onload = () => {
                ctx.drawImage(pic, 0, 0, 200, 200);
            }
        }
        items.forEach((currentValue, index) => {
            let pic = canvas.createImage();
            pic.src = currentValue.image; //可以是本地，也可以是网络图片
            pic.id = currentValue.id;
            pic.onload = () => {
                ctx.save();
                ctx.translate(0, 0);
                ctx.beginPath();
                ctx.translate(currentValue.x, currentValue.y); // 圆心坐标
                ctx.rotate(currentValue.angle * Math.PI / 180);
                // console.log(currentValue.x + " - " + currentValue.y);
                ctx.translate(-(currentValue.x), -(currentValue.y))
                ctx.drawImage(pic, currentValue.x - (currentValue.width * currentValue.scale) / 2, currentValue.y - (currentValue.height * currentValue.scale) / 2, currentValue.width * currentValue.scale, currentValue.height * currentValue.scale);
                ctx.restore();
            }
        });
    },
    clearActive() {
        let items = this.data.itemList;
        //找到点击的那个图片对象，并记录
        for (let i = 0; i < items.length; i++) {
            items[i].active = false;
        }
        this.setData({
            itemList: items
        });
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let that = this;
        wx.createSelectorQuery()
            .select('#canvas')
            .fields({
                node: true,
                size: true,
            })
            .exec(this.init.bind(this));

        wx.createSelectorQuery().select("#imgAvatar").boundingClientRect((res) => {
            that.setData({
                range: {
                    left: res.left,
                    right: res.right,
                    top: res.top,
                    bottom: res.bottom
                }
            })
        }).exec(res => {})

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})